<?php

namespace app\api\model;

use think\Model;

/**
 * 音频文件模型
 */
class Audio extends Model
{
    protected $name = 'api_audios';
    
    // 设置字段信息
    protected $schema = [
        'id'           => 'int',
        'room_id'      => 'int',
        'folder_id'    => 'int',
        'name'         => 'string',
        'display_name' => 'string',
        'file_path'    => 'string',
        'file_size'    => 'bigint',
        'duration'     => 'int',
        'format'       => 'string',
        'mime_type'    => 'string',
        'sort_order'   => 'int',
        'status'       => 'int',
        'create_time'  => 'bigint',
        'update_time'  => 'bigint',
    ];

    // 自动时间戳（毫秒）
    protected $autoWriteTimestamp = false;

    // 状态常量
    const STATUS_NORMAL = 1;  // 正常
    const STATUS_DELETED = 0; // 已删除

    /**
     * 获取所属文件夹
     */
    public function folder()
    {
        return $this->belongsTo(Folder::class, 'folder_id', 'id');
    }

    /**
     * 获取指定房间和文件夹的音频文件
     */
    public static function getAudiosByFolder($roomId, $folderId = null)
    {
        $query = self::where('room_id', $roomId)
            ->where('status', self::STATUS_NORMAL);
            
        if ($folderId === null) {
            $query->whereNull('folder_id');
        } else {
            $query->where('folder_id', $folderId);
        }
        
        return $query->order('sort_order', 'asc')
            ->order('create_time', 'desc')
            ->select();
    }

    /**
     * 移动音频文件到指定文件夹
     */
    public function moveToFolder($newFolderId)
    {
        $oldFolderId = $this->folder_id;
        
        // 更新音频文件的文件夹
        $this->save([
            'folder_id' => $newFolderId,
            'update_time' => time() * 1000
        ]);
        
        // 更新原文件夹的音频数量统计
        if ($oldFolderId) {
            $oldFolder = Folder::find($oldFolderId);
            if ($oldFolder) {
                $oldFolder->updateAudioCount();
            }
        }
        
        // 更新新文件夹的音频数量统计
        if ($newFolderId) {
            $newFolder = Folder::find($newFolderId);
            if ($newFolder) {
                $newFolder->updateAudioCount();
            }
        }
        
        return true;
    }

    /**
     * 软删除音频文件
     * @param bool $updateFolderCount 是否更新文件夹统计（批量删除时可设为false，统一更新）
     */
    public function softDelete($updateFolderCount = true)
    {
        $this->save([
            'status' => self::STATUS_DELETED,
            'update_time' => time() * 1000
        ]);
        
        // 更新文件夹的音频数量统计
        if ($updateFolderCount && $this->folder_id) {
            $folder = $this->folder;
            if ($folder) {
                $folder->updateAudioCount();
            }
        }
        
        return true;
    }

    /**
     * 重命名音频文件
     */
    public function rename($newName, $newDisplayName)
    {
        return $this->save([
            'name' => $newName,
            'display_name' => $newDisplayName,
            'update_time' => time() * 1000
        ]);
    }

    /**
     * 格式化文件大小
     */
    public function getFormattedSize()
    {
        $size = $this->file_size;
        
        if ($size < 1024) {
            return $size . 'B';
        } elseif ($size < 1024 * 1024) {
            return round($size / 1024, 1) . 'KB';
        } else {
            return round($size / (1024 * 1024), 1) . 'MB';
        }
    }

    /**
     * 格式化播放时长
     */
    public function getFormattedDuration()
    {
        $duration = $this->duration;
        $minutes = floor($duration / 60);
        $seconds = $duration % 60;
        
        return sprintf('%d:%02d', $minutes, $seconds);
    }

    /**
     * 获取音频文件的完整URL
     */
    public function getFullUrl()
    {
        // 如果是七牛云存储，返回完整URL
        if (strpos($this->file_path, 'http') === 0) {
            return $this->file_path;
        }
        
        // 否则拼接域名
        return config('app.domain') . $this->file_path;
    }

    /**
     * 检查音频格式是否支持
     */
    public static function isSupportedFormat($format)
    {
        $supportedFormats = ['mp3', 'wav', 'm4a', 'aac', 'ogg'];
        return in_array(strtolower($format), $supportedFormats);
    }

    /**
     * 获取MIME类型
     */
    public static function getMimeType($format)
    {
        $mimeTypes = [
            'mp3' => 'audio/mpeg',
            'wav' => 'audio/wav',
            'm4a' => 'audio/m4a',
            'aac' => 'audio/aac',
            'ogg' => 'audio/ogg',
        ];
        
        return $mimeTypes[strtolower($format)] ?? 'audio/mpeg';
    }
}
